/**
 * Copyright 2009 Takahiko Ito
 *
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.unigram.oluolu.rqe;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.Vector;
import java.util.Arrays;

import org.unigram.oluolu.common.Query;

/**
 * Extract related query pairs.  
 */
public class RelatedCandidateExtractionReducer extends
        Reducer<Text, Query, Text, Text> {

    /** maximum time of one session. */
    private long timeRange;
    
    /** maximum size of queries for one user. */
    private long maxItemSize;

    /**
     * Reduce method.
     * 
     * @param key query string
     * @param values candidate queries
     * @param context Context to flush results
     * @throws IOException -
     * @throws InterruptedException -
     */
    @Override
    public final void reduce(final Text key,
            final Iterable<Query> values, final Context context)
            throws IOException, InterruptedException {
        /* store and sort */
        Vector<Query> queries = new Vector<Query>();
        for (Query query : values) {
            queries.add(new Query(new Text(query.getQueryString()),
                    new LongWritable(query.getDate().get())));
        }
        Object[] queryArray = queries.toArray();
        Arrays.sort(queryArray);

        /* check: one user should not contribute too much */
        if (queryArray.length > maxItemSize) {
            return;
        }

        /* extract related candidate queries */
        for (int i = 0; i < queryArray.length; i++) {
            Query target = (Query) queryArray[i];
            LongWritable targetTime = target.getDate();
            String targetQueryStr = target.getQueryString().toString();
            for (int j = i + 1; j < queryArray.length; j++) {
                Query candidate = (Query) queryArray[j];
                LongWritable candidateTime = candidate.getDate();
                String candidateQueryStr
                    = candidate.getQueryString().toString();
                if (Math.abs(candidateTime.get()
                            - targetTime.get()) < timeRange) {
                    if (!targetQueryStr.equals(candidateQueryStr)) {
                        context.write(target.getQueryString(), candidate
                                .getQueryString());
                    }
                } else {
                    break;
                }
            }
        }
    }

    
    /**
     * Called once before running reduce to build settings 
     * such as threshold of time range for one sesion.
     *
     * @param context containing needed properties.
     */
    @Override
    public final void setup(final Context context) {
        Configuration jc = context.getConfiguration();
        timeRange = RqeConstants.DEFAULT_RQE_TIME_RANGE;
        maxItemSize = RqeConstants.DEFAULT_RQE_MAX_QUERY_NUMBER;
        if (context == null || jc == null) {
            /* added default configuration for testing */
            jc = new Configuration();
        }
        timeRange = jc.getLong(RqeConstants.RQE_TIME_RANGE,
                RqeConstants.DEFAULT_RQE_TIME_RANGE);
        maxItemSize = jc.getLong(RqeConstants.RQE_MAX_QUERY_NUMBER,
                RqeConstants.DEFAULT_RQE_MAX_QUERY_NUMBER);
    }
}

// 